import types from './mutation-types'
import { Fetch } from '@/utils/http_common'
import auth from '@/utils/auth'

const actions = {
  // 实际用到的登陆接口
  userLogin({ commit, dispatch }, payload) {
    let loginUrl = payload.type ? 'sign_in' : 'login'

    return new Promise((resolve, reject) => {
      Fetch.post(loginUrl, payload.user)
        .then(res => {
          if (res) {
            auth.setLocalStorage('CMS-TOKEN', res.token)
            auth.setLocalStorage('CMS-USER', res.user)

            commit(types.SET_USER, {
              token: res.token,
              user: res.user
            })

            resolve(true)
          }
        })
        .catch(error => {
          console.log('---登录---', error)
          reject(false)
        })
    })
  },

  logoutAction({ commit }) {
    auth.deleteLocalStorage('CMS-TOKEN')
    auth.deleteLocalStorage('CMS-USER')
    commit(types.LOGOUT)
  }
}

export default actions
